package cn.elvea.config;

import cn.elvea.security.ShiroFilterChainManager;
import cn.elvea.security.ShiroSecurityRealm;
import cn.elvea.utils.SpringContextHolder;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.BeansException;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Import;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
@Import(Config.class)
public class WebSecurityConfig implements ApplicationContextAware {


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        /*
        try {
            final Realm realm = (Realm) applicationContext.getBean("realm");
            final DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) applicationContext.getBean("securityManager");
            securityManager.setRealm(realm);
        } catch (Exception e) {
            throw new Error("Critical system error", e);
        }
        */
    }

    // --------------  Shiro Cofig --------------
    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter() throws Exception {
        Map<String, Filter> filters = new HashMap<>();
        filters.put("authc", getAuthFilter());
        filters.put("logout", getLogoutFilter());

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        shiroFilterFactoryBean.setSuccessUrl("/");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroFilterChainManager().getFilterChainDefinitionMap());
        shiroFilterFactoryBean.setFilters(filters);
        return shiroFilterFactoryBean;
    }

    @Bean
    public ShiroFilterChainManager shiroFilterChainManager() {
        Map<String, String> fcdMap = new LinkedHashMap<>();
        fcdMap.put("/static/**", "anon");
        fcdMap.put("/webjars/**", "anon");
        fcdMap.put("/captcha", "anon");
        fcdMap.put("/login", "authc");
        fcdMap.put("/logout", "logout");
        fcdMap.put("/**", "authc");

        ShiroFilterChainManager shiroFilterChainManager = new ShiroFilterChainManager();
        shiroFilterChainManager.setFilterChainDefinitionMap(fcdMap);
        return shiroFilterChainManager;
    }

    public Filter getAuthFilter() {
        return new FormAuthenticationFilter();
    }

    public Filter getLogoutFilter() {
        LogoutFilter filter = new LogoutFilter();
        filter.setRedirectUrl("/login");
        return filter;
    }

    @Bean(name = "securityManager")
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm());
        return securityManager;
    }

    @Bean(name = "shiroCacheManager")
    public CacheManager shiroEhcacheManager() {
        EhCacheCacheManager ehCacheCacheManager = SpringContextHolder.getBean("ehCacheCacheManager");
        System.out.println("...................................");
        System.out.println(ehCacheCacheManager.getCacheManager());
        System.out.println("...................................");
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManager(ehCacheCacheManager.getCacheManager());
        return cacheManager;
    }

    @Bean(name = "realm")
    @DependsOn("lifecycleBeanPostProcessor")
    public AuthorizingRealm realm() {
        ShiroSecurityRealm realm = new ShiroSecurityRealm();
        return realm;
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    @DependsOn(value = "lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
        return authorizationAttributeSourceAdvisor;
    }
}
